import authoriry from '@/utils/authority'

let { token = '', user = {} } = authoriry.get() || {}

const state = {
  isLogin: !!token,
  token,
  user
}

const getters = {
  user(state) {
    return state
  }
}

const mutations = {
  SET_USER: (state, payload) => {
    Object.entries(payload).forEach(([key, value]) => {
      state[key] = value
    })
  },
  SAVE_INFO: (state, payload) => {
    const { user, token } = payload
    state.user = user
    state.token = token
  }
}

const actions = {
  // 登录
  login({ state, commit }, data) {
    const { user = state.user, token = state.token } = data
    commit('SAVE_INFO', {
      user,
      token
    })
    authoriry.set({ user, token, maxAge: null })
  },

  // 登出
  logout({ commit }) {
    commit('SET_USER', {
      token: null,
      user: {}
    })
    localStorage.clear()
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}
